var operateItem = '';
//每页的最大数量
var itemMax = 6;
//当前页面
var nowPage = 1;
var firstItem = itemMax * (nowPage - 1);
var lastItem = itemMax * (nowPage);
//判断添加的班级内容是否有错（若有错不能提交）
var addClaItem = {
    'name': false,
    'teacher': false,
    'teacherTel': false,
    'lifeteacher': false,
    'lifeteacherTel': false,

};
var nameExist=false;
//判断编辑的班级内容是否有错（若有错不能提交）
//添加班级的json
// var editClaItem = {
//     'name': false,
//     'teacher': false,
//     'teacherTel': false,
//     'lifeteacher': false,
//     'lifeteacherTel': false,
// };
var oDefaultedit=$('.defaultedit')

var addClaJson = {};
// var editClaJson = {};
var getArr = JSON.parse(localStorage.getItem('classJson'));
//获取学生数组
var getStuArr = JSON.parse(localStorage.getItem('studentJson'));

//创建行
function countNum(name) {
    var num = 0;
    $.each(getStuArr, function (index, value) {
        if (value.class == name) {
            num++;
        }
    });
    return num;

}

$.each(getArr, function (index, value) {
    if (index >= firstItem && index < lastItem) {
        createList($('.table1'), index, value);
    }
});

//创建分页
createPage();

function createPage() {
    var read = JSON.parse(localStorage.getItem('classJson'));
    $('.pagination').append('<li><a href="javascript:;" id="leftPage"><span style="font-size: 14px;">&laquo;</span></a></li>');
    for (var i = 0; i < Math.ceil(read.length / itemMax); i++) {
        $('.pagination').append('<li><a href="javascript:;" class="pageNum" id="' + (i + 1) + '">' + (i + 1) + '</a></li>');
    }
    $('.pagination').append('<li><a href="javascript:;" id="rightPage"><span style="font-size: 14px;">&raquo;</span></a></li>');
}

function createList(obj, index, value) {
    $('.table1').append('<tr id="' + value.name + '">' +
        '<td>' + (index + 1) + '</td><td>' + value.name + '</td><td>' + value.teacher + '</td><td>' + value.teacherTel + '</td><td>' + value.lifeteacher + '</td><td>' + value.lifeteacherTel + '</td><td>' + countNum(value.name) +
        '</td><td><div class="class-operate">' +
        '<button type="button" class="btn btn-primary btn-sm edit" data-toggle="modal" data-target="#classEdit">编辑</button>' +
        '<button type="button" class="btn btn-warning btn-sm delete"  data-toggle="modal" data-target="#classDelete">删除</button>' +
        '</div></td><td><button type="button" class="btn btn-primary btn-sm check" data-toggle="modal" data-target="#ClassCheck">查看班级人员</button></td>'
    );
}

//为分页添加事件
$('.pagination').on('click', 'a', function () {
    if ($(this).attr('id') == 'leftPage') {
        if ($('.pageNum[id=' + nowPage + ']').parent().prev().children().eq(0).attr('id') != 'leftPage') {
            nowPage -= 1;
            $("tr:not('.headline')").remove();
            firstItem = itemMax * (nowPage - 1);
            lastItem = itemMax * (nowPage);
            var read = JSON.parse(localStorage.getItem('classJson'));
            $.each(read, function (index, value) {
                if (index >= firstItem && index < lastItem) {
                    createList($('.table1'), index, value);
                }
            })
        }
    } else if ($(this).attr('id') == 'rightPage') {
        if ($('.pageNum[id=' + nowPage + ']').parent().next().children().eq(0).attr('id') != 'rightPage') {
            nowPage += 1;
            $("tr:not('.headline')").remove();
            firstItem = itemMax * (nowPage - 1);
            lastItem = itemMax * (nowPage);
            var read = JSON.parse(localStorage.getItem('classJson'));
            $.each(read, function (index, value) {
                if (index >= firstItem && index < lastItem) {
                    createList($('.table1'), index, value);
                }
            })
        }
    } else {
        $("tr:not('.headline')").remove();
        nowPage = parseInt($(this).attr('id'));
        firstItem = itemMax * (nowPage - 1);
        lastItem = itemMax * (nowPage);
        var read = JSON.parse(localStorage.getItem('classJson'));
        $.each(read, function (index, value) {
            if (index >= firstItem && index < lastItem) {
                createList($('.table1'), index, value);
            }
        })
    }
});
//为编辑 删除 查看人员添加事件（记录操作的是哪一行）
$('.table1').on('click', 'button', function () {
    //指定将要操作哪行
    operateItem = $(this).parents('tr').attr('id');
    if ($(this).hasClass('check')) {
        $('.checkList').remove();
        var read = JSON.parse(localStorage.getItem('studentJson'));
        $.each(read, function (index, value) {
            if (value.class == operateItem) {
                $('.table2').append('<tr class="checkList"><td>' + value.name
                    + '</td><td>' + value.sex
                    + '</td><td>' + value.class
                    + '</td><td>' + value.birth
                    + '</td><td>' + value.parent
                    + '</td><td>' + value.phone
                    + '</td><td>' + value.address
                    + '</td>')
            }
        })
    }
    if ($(this).hasClass('edit')) {
        oDefaultedit.eq(0).val($(this).parent().parent().parent().children().eq(1).text());
        oDefaultedit.eq(1).val($(this).parent().parent().parent().children().eq(2).text());
        oDefaultedit.eq(2).val($(this).parent().parent().parent().children().eq(3).text());
        oDefaultedit.eq(3).val($(this).parent().parent().parent().children().eq(4).text());
        oDefaultedit.eq(4).val($(this).parent().parent().parent().children().eq(5).text())
    }
});
//为模态框classDelete 确定按钮添加事件
$('#deletesResure').on('click', function () {
    $("tr:not('.headline')").remove();
    itemResort();
    removeJson(operateItem);
    var read = JSON.parse(localStorage.getItem('classJson'));


    if(Math.ceil(read.length/itemMax)<nowPage){
        nowPage-=1;
    }
    console.log(nowPage)
    firstItem = itemMax * (nowPage - 1);
    lastItem = itemMax * (nowPage);
    $('#classDelete').modal('hide');
    $.each(read, function (index, value) {
        if (index >= firstItem && index < lastItem) {
            createList($('.table1'), index, value);
        }
    });
    itemResort(nowPage);
    $('.pagination').children().remove();
    $('.pagination').html('');
    createPage();
});
//为模态框classEdit 确定按钮添加事件

$('#saveEdit').on('click', function () {
	
    var name=$('input[name="name"]').val();
	var teacher=$('input[name="teacher"]').val();
	var teacherTel=$('input[name="teacherTel"]').val();
	var lifeteacher=$('input[name="lifeteacher"]').val();
	var lifeteacherTel=$('input[name="lifeteacherTel"]').val();
	
	console.log(name)
	console.log(teacher)
		
	console.log(teacherTel)
	console.log(lifeteacher)
    console.log(lifeteacherTel)
   
	if(getRegMsg('name').test(name)&&getRegMsg('teacher').test(teacher)&&getRegMsg('teacherTel').test(teacherTel)&&getRegMsg('lifeteacher').test(lifeteacher)&&getRegMsg('lifeteacherTel').test(lifeteacherTel)&&nameExist==false){ 
    var read = JSON.parse(localStorage.getItem('classJson'));
    $("tr:not('.headline')").remove();
    $.each(read, function (index, value) {
        if (value.name == operateItem) {
            value.name = name;
            value.teacher = teacher;
            value.teacherTel = teacherTel;
            value.lifeteacher = lifeteacher;
            value.lifeteacherTel = lifeteacherTel;
        }
        firstItem = itemMax * (nowPage - 1);
        lastItem = itemMax * (nowPage);
        if (index >= firstItem && index < lastItem) {
            createList($('.table1'), index, value);
        }
    });
    itemResort(nowPage);
    localStorage.setItem("classJson", JSON.stringify(read));

    $('#classEdit').modal('hide')
	}else{
		alert('输入有误')
	}
});

//检测classEdit input 输入值是否输入正确
$('.classEditInput').on('input', function () {
    var itemsName = $(this).attr('name');
    var itemsValue = $(this).val();
    var reg = getRegMsg(itemsName);
    var read = JSON.parse(localStorage.getItem('classJson'));
    var textValue = $('.classEditInput').eq(0).val();
    var that = $(this);
    if (reg.test(itemsValue)) {
        $(this).parent().next().next().css('display', 'none');
    } else {
        $(this).parent().next().next().css('display', 'block');
    }
    $.each(read, function (index, value) {
        if (that.attr('name') == 'name') {
            if (value.name == textValue && itemsName == 'name' && value.name != operateItem) {
                that.parent().next().next().text('该班级已存在');
                that.parent().next().next().css('display', 'block');
				nameExist=true;
                return false;
            } else {
                if (reg.test(itemsValue)) {
                    that.parent().next().next().css('display', 'none');
					nameExist=false;
                } else {
                    that.parent().next().next().text('班级名称长度在3-10字之间!');
					nameExist=false;
                }
            }
        }
    })
});

//重新排序函数
function itemResort(page) {
    for (var i = 0; i < $('.table1').children().children().length; i++) {
        if (i >= 1) {
            $('.table1').children().children().eq(i).children().eq(0).text((page-1)*itemMax+i);
        }
    }
}

//删除对应JSON(以班级名称作为主键)
function removeJson(name) {
    var removeName = name;
    var read = JSON.parse(localStorage.getItem('classJson'));
    $.each(read, function (index, value) {
        if (value.name == removeName) {
            read.splice(index, 1);
            var nowPage = Math.ceil(index / 2);
            localStorage.setItem("classJson", JSON.stringify(read));
            return false;
        }
    })
}

//判断输入值是否符合正则，同时将正确的输入值传入将要添加进班级数组的json
$('.addClassInput').on('input', function () {
    var itemsName = $(this).attr('id');
    var itemsValue = $(this).val();
    var reg = getRegMsg(itemsName);
    var read = JSON.parse(localStorage.getItem('classJson'));
    var textValue = $('.addClassInput').eq(0).val();
    var that = $(this);
    if (reg.test(itemsValue)) {
        $(this).parent().next().next().css('display', 'none');
        addClaItem[itemsName] = true;
        addClaJson[itemsName] = itemsValue;
    } else {
        $(this).parent().next().next().css('display', 'block');
        addClaJson[itemsName] = '';
        addClaItem[itemsName] = false;
    }
    $.each(read, function (index, value) {
        if (that.attr('id') == 'name') {
            if (value.name == textValue) {
                that.parent().next().next().text('该班级已存在');
                that.parent().next().next().css('display', 'block');
                addClaItem['name'] = false;
                return false;
            } else {
                if (reg.test(itemsValue)) {
                    that.parent().next().next().css('display', 'none');
                    addClaItem[itemsName] = true;
                    addClaJson[itemsName] = itemsValue;
                } else {
                    that.parent().next().next().text('班级名称长度在3-10字之间!');
                    addClaJson[itemsName] = '';
                    addClaItem[itemsName] = false;
                }
            }
        }
    })
});

//获取对应正则（以input id为函数参数）
function getRegMsg(name) {
    var reg = '';
    switch (name) {
        case 'name':
            reg = depNameReg;
            break;
        case 'teacher':
            reg = nameReg;
            break;
        case 'teacherTel':
            reg = phoneNumberReg;
            break;
        case 'lifeteacher':
            reg = nameReg;
            break;
        case 'lifeteacherTel':
            reg = phoneNumberReg;
            break;

    }
    return reg;
}

//保存添加的班级
$('#saveCla').on('click', function () {
    var isExist = false;
    for (var key in addClaItem) {
        if (addClaItem[key] == false) {
            alert('添加错误或未添加完全！');
            return;
        }
    }
    var read = JSON.parse(localStorage.getItem('classJson'));
    read.unshift(addClaJson);
    $("tr:not('.headline')").remove();
    $.each(read, function (index, value) {
        if (index < itemMax) {
            createList($('.table1'), index, value);
        }
    });
    itemResort(nowPage);
    localStorage.setItem("classJson", JSON.stringify(read));
    $('#addClassModel').modal('hide');
    $('.addClassInput').val('');
    $('.pagination').html('');
    createPage();

});